// app/model/plugin_data_item_model.js
'use strict';

module.exports = app => {
  const { INTEGER, STRING, TEXT, DATE, JSON, BIGINT } = app.Sequelize;
  
  const PluginDataItem = app.model.define('plugin_data_item', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    itemId: {
      type: STRING(100),
      allowNull: false,
      unique: true,
      field: 'item_id',
      comment: '数据项ID'
    },
    batchId: {
      type: STRING(100),
      allowNull: false,
      field: 'batch_id',
      comment: '批次ID'
    },
    url: {
      type: TEXT,
      allowNull: false,
      field: 'url',
      comment: '请求URL',
      validate: {
        len: {
          args: [1, 2000],
          msg: 'URL长度必须在1-2000字符之间'
        }
      }
    },
    method: {
      type: STRING(10),
      allowNull: false,
      field: 'method',
      comment: 'HTTP方法',
      validate: {
        isIn: {
          args: [['GET', 'POST', 'PUT', 'DELETE', 'PATCH']],
          msg: 'HTTP方法必须是GET/POST/PUT/DELETE/PATCH之一'
        }
      }
    },
    category: {
      type: STRING(50),
      allowNull: true,
      field: 'category',
      comment: '数据分类（bank/order/invoice）',
      validate: {
        isIn: {
          args: [['bank', 'sales_order', 'purchase_order', 'invoice', 'incoming_invoice', 'outgoing_invoice', 'announcement', 'unknown']],
          msg: '数据分类无效'
        }
      }
    },
    status: {
      type: STRING(20),
      allowNull: false,
      defaultValue: 'pending',
      field: 'status',
      comment: '处理状态（pending/processed/failed）',
      validate: {
        isIn: {
          args: [['pending', 'processed', 'failed']],
          msg: '状态值无效'
        }
      }
    },
    requestData: {
      type: JSON,
      allowNull: true,
      field: 'request_data',
      comment: '请求数据',
      get() {
        // 数据读取时进行安全检查
        const data = this.getDataValue('requestData');
        if (data && typeof data === 'string') {
          try {
            return JSON.parse(data);
          } catch (e) {
            return data;
          }
        }
        return data;
      },
      set(value) {
        // 数据存储时进行大小限制
        if (value && typeof value === 'object' && typeof JSON.stringify === 'function') {
          try {
            const jsonStr = JSON.stringify(value);
            if (jsonStr.length > 100000) { // 100KB限制
              throw new Error('请求数据过大');
            }
            this.setDataValue('requestData', jsonStr);
          } catch (e) {
            // 如果序列化失败，存储原始值
            this.setDataValue('requestData', value);
          }
        } else {
          this.setDataValue('requestData', value);
        }
      }
    },
    responseData: {
      type: JSON,
      allowNull: true,
      field: 'response_data',
      comment: '响应数据',
      get() {
        // 数据读取时进行安全检查
        const data = this.getDataValue('responseData');
        if (data && typeof data === 'string') {
          try {
            return JSON.parse(data);
          } catch (e) {
            return data;
          }
        }
        return data;
      },
      set(value) {
        // 数据存储时进行大小限制
        if (value && typeof value === 'object' && typeof JSON.stringify === 'function') {
          try {
            const jsonStr = JSON.stringify(value);
            if (jsonStr.length > 1000000) { // 1MB限制
              throw new Error('响应数据过大');
            }
            this.setDataValue('responseData', jsonStr);
          } catch (e) {
            // 如果序列化失败，存储原始值
            this.setDataValue('responseData', value);
          }
        } else {
          this.setDataValue('responseData', value);
        }
      }
    },
    ruleInfo: {
      type: JSON,
      allowNull: true,
      field: 'rule_info',
      comment: '规则信息',
      get() {
        const data = this.getDataValue('ruleInfo');
        if (data && typeof data === 'string') {
          try {
            return JSON.parse(data);
          } catch (e) {
            return data;
          }
        }
        return data;
      },
      set(value) {
        if (value && typeof value === 'object' && typeof JSON.stringify === 'function') {
          try {
            const jsonStr = JSON.stringify(value);
            if (jsonStr.length > 10000) { // 10KB限制
              throw new Error('规则信息过大');
            }
            this.setDataValue('ruleInfo', jsonStr);
          } catch (e) {
            // 如果序列化失败，存储原始值
            this.setDataValue('ruleInfo', value);
          }
        } else {
          this.setDataValue('ruleInfo', value);
        }
      }
    },
    processedAt: {
      type: DATE,
      allowNull: true,
      field: 'processed_at',
      comment: '处理时间'
    },
    createdAt: {
      type: DATE,
      allowNull: false,
      field: 'created_at',
      comment: '创建时间'
    },
    updatedAt: {
      type: DATE,
      allowNull: false,
      field: 'updated_at',
      comment: '更新时间'
    },
    errorMessage: {
      type: TEXT,
      allowNull: true,
      field: 'error_message',
      comment: '错误信息',
      validate: {
        len: {
          args: [0, 1000],
          msg: '错误信息长度不能超过1000字符'
        }
      }
    }
  }, {
    tableName: 'plugin_data_items',
    comment: '插件数据项表',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    indexes: [
      {
        fields: ['batch_id']
      },
      {
        fields: ['category']
      },
      {
        fields: ['status']
      },
      {
        fields: ['created_at']
      },
      {
        fields: ['batch_id', 'category', 'status']
      }
    ],
    // 模型级别的验证
    validate: {
      // 确保数据一致性
      dataConsistency() {
        if (this.category && !['bank', 'sales_order', 'purchase_order', 'invoice', 'incoming_invoice', 'outgoing_invoice', 'announcement', 'unknown'].includes(this.category)) {
          throw new Error('无效的数据分类');
        }
        
        if (this.status && !['pending', 'processed', 'failed'].includes(this.status)) {
          throw new Error('无效的状态值');
        }
      }
    }
  });
  
  return PluginDataItem;
};